package Servlet;

import Dao.ManagerDao;
import Dao.UserDao;
import Table.Manager;
import Table.User;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取输入的信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode1 = req.getParameter("checkCode");
        //获取随机生成的验证码
        String checkCode = (String) req.getSession().getAttribute("checkCode");
        //访问数据库
        User user = UserDao.FindUser(username, password);
        Manager manager = ManagerDao.FindManager(username, password);
        PrintWriter out = resp.getWriter();
        HashMap<String, String> map = new HashMap<>();
        //忽略大小写
        if (checkCode.equalsIgnoreCase(checkCode1)) {
            map.put("user_Error", "");
            map.put("checkCode_Error", "");
            if (user == null && manager == null) {
                map.put("user_Error", "用户名或密码不正确!");
            } else if (user != null) {
                map.put("user_Error", "");
                map.put("checkCode_Error", "");
                map.put("jump", "1");
                req.getSession().setAttribute("user", user);
            } else if (manager != null) {
                map.put("user_Error", "");
                map.put("checkCode_Error", "");
                map.put("jump", "2");
                req.getSession().setAttribute("manager", manager);
            }
        } else {
            map.put("checkCode_Error", "验证码不正确!");
        }
        String s = JSON.toJSONString(map);
        resp.setContentType("application/json;charset=utf-8");
        out.println(s);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
